﻿using Domain.Entities;
using Domain.Misc;
using System.Net;
using System.Net.Mail;

namespace Domain.Mail
{
    public class MailSender
    {
        private MailMessage mailMessage;
        private MailSettings mailSettings;

        public MailSender(MailParser mailParser, MailSettings mailSettings)
        {
            mailMessage = mailParser.Parse();
            mailMessage.From = new MailAddress(mailSettings.FromAddress, mailSettings.FromDisplayName);
            this.mailSettings = mailSettings;
        }

        public MailSender(MailParser mailParser)
        {
            mailMessage = mailParser.Parse();

            Settings settings = BoardSettingsManager.Instance.Settings;
            mailSettings = new MailSettings();
            mailSettings.FromAddress = settings.EmailFromAddress;
            mailSettings.FromDisplayName = settings.EmailFromDisplayName;
            mailSettings.SmtpHost = settings.EmailSmtpHost;
            mailSettings.SmtpPort = settings.EmailSmtpPort;
            mailSettings.SmtpUsername = settings.EmailSmtpUsername;
            mailSettings.SmtpPassword = settings.EmailSmtpPassword;
            mailSettings.EnableSsl = settings.EmailEnableSsl;
            mailMessage.From = new MailAddress(mailSettings.FromAddress, mailSettings.FromDisplayName);
        }

        public void AddRecipient(string address)
        {
            mailMessage.To.Add(new MailAddress(address));
        }

        public void Send()
        {
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = mailSettings.SmtpHost;
            smtpClient.Port = mailSettings.SmtpPort;
            smtpClient.EnableSsl = mailSettings.EnableSsl;
            smtpClient.Credentials = new NetworkCredential(mailSettings.SmtpUsername, mailSettings.SmtpPassword);
            smtpClient.Send(mailMessage);
        }
    }
}
